<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输角色名称" clearable v-model="name" @clear="searchRole">
            <el-button slot="append" icon="el-icon-search" @click="searchRole"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="name"></el-table-column>
        <el-table-column label="创建时间" prop="insertTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="warning" size="mini" @click="authorityPer(scope.row)">授权</el-button>
            <el-button type="primary" size="mini" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[6 , 12, 24]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>
    <!--添加角色-->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addRoleFormClose">
      <el-form
          :model="addRoleForm"
          :rules="addRoleFormRules"
          ref="addRoleFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addRoleForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRole">确 定</el-button>
                <el-button @click="addRoleFormClose">取 消</el-button>
      </span>
    </el-dialog>
    <!--修改角色-->
    <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editRoleFormClose"
    >
      <el-form
          :model="editRoleForm"
          :rules="editRoleFormRules"
          ref="editRoleFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editRoleForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="editRole">确 定</el-button>
                <el-button @click="editRoleFormClose">取 消</el-button>
            </span>
    </el-dialog>

    <!--授权-->
    <el-dialog
        title="角色授权"
        :visible.sync="authrityDialogVisible"
        width="50%"
        @close="authrityFormClose"
        :close-on-click-modal="false"
    >
      <el-form
          :model="authrityRoleForm"
          :rules="authrityRoleFormRules"
          ref="authrityRoleFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="authrityRoleForm.name" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="权限" prop="perCheckedIds">
          <el-tree
              :data="permissionList"
              :props="defaultProps"
              :show-checkbox="true"
              ref="permissionTreeRef"
              node-key="id"
              :check-strictly="true"
              :default-expand-all="true"
              :default-checked-keys="defaultCheckedIds"
          >
          </el-tree>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="authorityRole">确 定</el-button>
                <el-button @click="cancelAuthority">取 消</el-button>
            </span>
    </el-dialog>

    <!--        {{defaultCheckedIds}}-->
  </div>
</template>
<script>
export default {
  data() {
    return {
      authrityDialogVisible: false,
      addDialogVisible: false,
      editDialogVisible: false,
      pageNum: 1,
      pageSize: 6,
      name: "",
      roleList: [],
      total: 0,
      addRoleForm: {
        name: ""
      },
      addRoleFormRules: {
        name: [
          {required: true, message: "角色不能为空", trigger: "blur"}
        ]
      },
      editRoleForm: {
        id: -1,
        name: ""
      },
      editRoleFormRules: {
        name: [
          {required: true, message: "角色不能为空", trigger: "blur"}
        ]
      },
      //授权的对象
      authrityRoleForm: {
        id: '',
        name: '',
        perCheckedIds: []  //选中的权限
      },
      //授权验证
      authrityRoleFormRules: {},
      permissionList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultCheckedIds: [] //角色中原有的权限  反显
    };
  },
  computed: {
    defaultCheckedIdsComputed() {
      return this.defaultCheckedIds;
    }
  },
  methods: {
    //打开授权对话框
    authorityPer(row) {
      this.authrityDialogVisible = true;
      this.authrityRoleForm.id = row.id;
      this.authrityRoleForm.name = row.name;

      //1. 查询所有的权限
      this.defaultCheckedIds = [];
      //2.  查询当前 这个角色拥有的权限
      let url = "/permission/getPermissionId/" + row.id;
      this.$axios.get(url)
          .then(res => {
            if (res.data.code == 200) {
              console.log(res.data.data)
              this.defaultCheckedIds = res.data.data;
              /* this.$nextTick(a=>{
                   let t = this.$refs.permissionTreeRef ;
                   t.defaultCheckedKeys = res.data.data;
                   //this.$refs.permissionTreeRef.default-checked-keys = res.data.data ;
               })*/
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg,
                duration: 1000
              })
            }
          })
    },
    //关闭授权对话框
    authrityFormClose() {
      this.authrityDialogVisible = false;
      this.$refs.permissionTreeRef.setCheckedKeys([]);//取消树中 被选中的状态
    },
    //取消授权
    cancelAuthority() {
      this.authrityDialogVisible = false;
      //this.defaultCheckedIds = [];
      this.$refs.permissionTreeRef.setCheckedKeys([]); //取消树中 被选中的状态
    },
    //保存授权
    authorityRole() {
      let url = "/role/authority";
      //获取 选中的 节点的id
      let ids = this.$refs.permissionTreeRef.getCheckedKeys();
      if (ids.length < 1) {
        this.$message({
          type: "error",
          message: '请至少选中一个权限',
          duration: 1000
        })
        return;
      }
      this.authrityRoleForm.perCheckedIds = ids;
      this.$axios.put(url, this.authrityRoleForm)
          .then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: "success",
                message: res.data.msg,
                duration: 1000
              })
              this.authrityDialogVisible = false;
              this.initRole();
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
    },

    // 删除角色信息
    removeRoleById(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = "/role/del/" + id;
        this.$axios.delete(url)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1000
                })
                this.initRole();
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                  duration: 1000
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //添加角色
    addRoleFormClose() {
      this.addDialogVisible = false;
      this.$refs.addRoleFormRef.resetFields();
    },
    addRole() {
      this.$refs.addRoleFormRef.validate(valid => {
        if (!valid) {
          return;
        }

        let url = "/role/add";
        this.$axios.post(url, this.addRoleForm).then(res => {
          console.log(res)
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000
            })
            this.addDialogVisible = false;
            this.$refs.addRoleFormRef.resetFields();
            this.initRole();
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
              duration: 1000
            })
          }
        });
      })
    },
    //编辑角色
    showEditDialog(row) {
      this.editDialogVisible = true;
      this.editRoleForm.id = row.id;
      this.editRoleForm.name = row.name;
    },
    editRoleFormClose() {
      this.editDialogVisible = false;
      this.$refs.editRoleFormRef.resetFields();
    },

    editRole() {
      this.$refs.editRoleFormRef.validate(valid => {
        if (!valid) {
          return;
        }

        let url = "/role/modify";
        this.$axios.put(url, this.editRoleForm).then(res => {
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1000
            })
            this.editDialogVisible = false;
            this.$refs.editRoleFormRef.resetFields();
            this.initRole();
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
              duration: 1000
            })
          }
        });
      })
    },

    searchRole() {
      this.pageNum = 1;
      this.initRole();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNum = 1;
      this.initRole();
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.initRole();
    },

    initRole() {
      let url = "/role/list";
      this.$axios.get(url, {
        params: {
          now: this.pageNum,
          size: this.pageSize,
          name: this.name
        }
      }).then(res => {
        if (res.data.code == 200) {
          this.roleList = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.pageNum = res.data.data.pageNum;
          this.total = res.data.data.total;
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },

    //初始化加载菜单  先查询所有菜单
    loadMenus() {
      let url = "/permission/showAllMenu";
      this.$axios.get(url)
          .then(res => {
            if (res.data.code == 200) {
              this.permissionList = res.data.data;
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg,
                duration: 1000
              })
            }
          })
    }
  },
  created() {
    this.initRole();
    this.loadMenus();
  }
};
</script>
<style lang="less" scoped>
</style>